﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ObstacleManager : MonoBehaviour 
{
	[SerializeField]private GameObject maincamera = null;
	[SerializeField]private List<GameObject> obstables = new List<GameObject>();
//	[SerializeField]private GameObject obstable_one = null;
//	[SerializeField]private GameObject obstable_two = null;
//	[SerializeField]private GameObject obstable_three = null;

	void Update()
	{
		foreach(var v in obstables)
		{
			CheckDistanceFromCamera(v);
		}
//		CheckDistanceFromCamera (obstable_one);
//		CheckDistanceFromCamera (obstable_two);
//		CheckDistanceFromCamera (obstable_three);
	}

	void CheckDistanceFromCamera(GameObject go)
	{
		//float dis = Vector3.Distance (go.transform.position, maincamera.transform.position);
		float dis = go.transform.position.x - maincamera.transform.position.x;
		if(dis < -10f)
		{
			NewPosition (go);
		}
	}
	void NewPosition(GameObject go)
	{
//		float deltaX = Random.Range (23.1f, 37.9f);
//		float deltaY = Random.Range (-5.9f, 5.9f);
		float deltaX = randomVector2().x;
		float deltaY = randomVector2().y;
		float X = go.transform.position.x + deltaX;
		float Y = go.transform.position.y + deltaY;
		float Z = go.transform.position.z;
		Y = Mathf.Clamp (Y, -7.1f, 7.1f);

		Vector3 tempPostion = new Vector3(X, Y, Z);
		foreach(var g in obstables)
		{
			if(g.gameObject.name != go.gameObject.name)
			{
				bool bx = false;
				if(Mathf.Abs(g.transform.position.x - tempPostion.x)< 3f)
				{
					NewPosition (go);
					break;
				}else{
					bx = true;
				}
				if(Mathf.Abs(g.transform.position.y - tempPostion.y)< 2f)
				{
					NewPosition (go);
					break;
				}else{
					if ( bx )
					{
						go.transform.position = tempPostion;
						break;
					}

				}
			}

		}
		//go.transform.position = new Vector3(X, Y, Z);
	}
	Vector2 randomVector2()
	{
		float deltaX = Random.Range (23.1f, 37.9f);
		float deltaY = Random.Range (-5.9f, 5.9f);
		return new Vector2 (deltaX, deltaY);
	}
}
